package util

import (
	"io"
	"bytes"
	"strconv"
	"encoding/xml"
)

// 解析 xml 内容改为 map
func XmlToMap(data []byte) (map[string]string, error) {
	decoder := xml.NewDecoder(bytes.NewReader(data))
	xmlMap := make(map[string]string)
	tempKey := ""
	for {
		t, err := decoder.Token()
		if err == io.EOF {
			break
		} else if err != nil {
			return xmlMap, err
		}
		switch token := t.(type) {
		case xml.StartElement:
			tempKey = token.Name.Local
			if tempKey == "xml" {
				tempKey = ""
			}
			break
		case xml.EndElement:
			tempKey = ""
			break
		case xml.CharData:
			if tempKey != "" {
				xmlMap[tempKey] = string([]byte(token))
			}
			break
		}
	}
	return xmlMap, nil
}

func SliceAtoi(s []string) ([]int, error) {
	is := make([]int, 0)
	for _, a := range s {
		if a == "" {
			continue
		}
		i, err := strconv.Atoi(a)
		if err != nil {
			return nil, err
		}
		is = append(is, i)
	}
	return is, nil
}
